package net.eliga.sitechecker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.TagType;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class asg {
    private static final int thinkpadThreshold = 200;
    private static final int threshold = 193;
    private static String adminEmail;
    private static String adminSMS;
    private static String baseUrl;
    // 30 seconds
    private static int smallDelay = 1000 * 30;
    // 10 minutes
    private static int largeDelay = 1000 * 60 * 10;
    private static List<String> smsList;
    private static List<String> emailList;

    private static int delay;
    private static boolean sentErrorMessage;
    private static Configuration config;

    public static void main(String[] args) {

        configureSettings();
        // sendSubscriptionInfo();

        String urlString = "http://outlet.lenovo.com/laptops.html";
        while (true) {
            try {
                delay = smallDelay;
                checkAndSendMessage(urlString);
                sleep(delay);
            } catch (Exception e) {
                if (!sentErrorMessage) {

                    sentErrorMessage = sendErrorMessage(e);
                }
                e.printStackTrace();
            }
        }

    }

    private static void sendSubscriptionInfo() {
        sendMailToList(
                emailList,
                "Lenovo Deal Subscription",
                "You have been subscribed to an automated mailing list for Lenovo outlet deals. If you need to unsubscribe, send a mail to unsubscribe@peliga.com");
        sendMailToList(smsList, "Subscription",
                "You have been subscribed to Lenovo Outlet deals. to unsubscribe, mail to unsub@peliga.com");
    }

    private static void configureSettings() {
        try {
            config = new PropertiesConfiguration("config.properties");

            adminEmail = config.getString("adminEmail");
            adminSMS = config.getString("adminSMS");
            baseUrl = config.getString("baseUrl");
            smallDelay = config.getInt("smallDelay");
            largeDelay = config.getInt("largeDelay");
            smsList = config.getList("smsList");
            emailList = config.getList("emailList");

        } catch (ConfigurationException e1) {
            e1.printStackTrace();
            System.exit(1);
        }
    }

    private static void checkAndSendMessage(String urlString) throws IOException {
        String page = downloadURLAsString(urlString);
        processPage(page);
    }

    private static void processPage(String page) {

        Source source = new Source(page);

        List<Element> items = source.getAllElementsByClass("item");

        for (Element item : items) {
            String productName = item.getAllElementsByClass("product-name").get(0).getTextExtractor().toString();

            List<Element> prices = item.getAllElementsByClass("price");

            float lowPrice = Float.parseFloat(prices.get(prices.size() - 1).getTextExtractor().toString()
                    .replace("$", ""));

            List<Element> qtys = item.getAllElementsByClass("availability in-stock");
            int qty = 0;
            if (qtys.size() > 0) {
                qty = Integer.parseInt(qtys.get(0).getFirstElement("span").getTextExtractor().toString());
            }

            List<Element> descs = item.getAllElementsByClass("desc std");
            String desc = "";
            String link = "";
            if (descs.size() > 0) {
                desc = descs.get(0).getTextExtractor().toString();
                List<Element> links = descs.get(0).getAllElements("a");
                link = links.size() > 0 ? links.get(0).getAttributeValue("href") : "";
                //System.out.println(link);
            }

            System.out.print(qty);
            System.out.print(" " + productName + " @");
            System.out.print(lowPrice + " * ");

            if (matchConditions(lowPrice, qty, productName, desc)) {
                sendMessage(productName, lowPrice, qty);
                delay = largeDelay;
                break;
            }
        }
        System.out.println();
    }

    private static boolean matchConditions(float lowPrice, int qty, String productName, String desc) {
        boolean status = false;
        if (lowPrice < threshold && qty > 0) {
            status = true;
        } else if (productName.toLowerCase().contains("thinkpad") && lowPrice < thinkpadThreshold && qty > 0) {
            status = true;
        } else if (desc.contains("tablet")) {
            status = true;
        }
        return status;
    }

    private static void sendMessage(String productName, float lowPrice, int qty) {

        String message = productName + " $" + lowPrice + " Qty:" + qty;
        System.out.println("### sending sms - " + message);

        sendMailToList(smsList, "now", message);

        message = productName + " $" + lowPrice + " Qty:" + qty;
        System.out.println("### sending email - " + message);

        sendMailToList(emailList, "Lenovo Deal", message);
    }

    private static void sendMailToList(List<String> mailingList, String subject, String message) {
        for (String mailId : mailingList) {
            sendMail(mailId, subject, message);
        }

    }

    private static boolean sendErrorMessage(Exception e) {
        return sendMail(adminEmail, "ERROR", e.toString());
    }

    private static boolean sendMail(String email, String subject, String message) {
        try {
            String sendUrl = baseUrl + email + "&subject=" + subject + "&message=" + message
                    + "&headers=From: Lenovo@Deal.com%0D%0AX-Mailer: php";
            String response = downloadURLAsString(sendUrl.replaceAll(" ", "%20"));
            System.out.println(response);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static void sleep(long timeInMillis) {
        try {
            Thread.sleep(timeInMillis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String downloadURLAsString(String urlString) throws IOException {
        URL url = new URL(urlString);

        StringBuffer buffer = new StringBuffer();

        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            buffer.append(inputLine + "\n");
        }

        in.close();

        return buffer.toString();

    }

}